<template>
  <div class="main">
    <div class="header">
      <div class="logo">
        <span class="big">
          <el-avatar style="vertical-align:middle;" :size="45" :src="userAvatar"></el-avatar>
          <span>{{loginContext.getLoginContext().loginName}}</span>
        </span>
        <span class="min">
          <el-avatar style="vertical-align:middle;" :size="45" :src="userAvatar"></el-avatar>
        </span>
      </div>
      <span class="header-btn" @click="hiddenSidebar">
        <i class="el-icon-menu"></i>
      </span>
      <span class="header-btn" v-if="oneLevelMenus != null && oneLevelMenus.length > 0" @click="loadAsideMenu(menu)"
        :key="menu.code" v-for="menu in oneLevelMenus" :style="siteName == menu.description ? 'color:#ffd04b;' : ''">
        {{menu.description}}
      </span>
      <div class="right">
        <span class="header-btn" @click="screenfullToggle">
          <li class="el-icon-full-screen"></li>
        </span>
        <el-dropdown @command="handleCommandMessage">
          <span class="header-btn">
            <el-badge is-dot type="warning">
              消息中心
            </el-badge>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="A102107">
              <i style="padding-right: 5px" class="el-icon-message"></i>
              <el-badge :value="myUnreadNoticeCount.A102107" :max="10">
                通知
              </el-badge>
            </el-dropdown-item>
            <el-dropdown-item command="A102108">
              <i style="padding-right: 5px" class="el-icon-warning"></i>
              <el-badge :value="myUnreadNoticeCount.A102108" :max="10">
                报警
              </el-badge>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-dropdown v-if="loginContext.getLoginContext().userType == 'A100411'" @command="switchProjectByUser">
          <span class="header-btn">
            我的社区
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item :command="item.id" :key="item.id" v-for="item in projectList" :style="(loginContext.getLoginContext().projectId == item.id) ? 'color:#409EFF;' : ''">
              <i style="padding-right: 5px" class="el-icon-caret-right"></i>{{item.name}}
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-dropdown @command="handlePersonalCenter">
          <span class="header-btn">
            更多选项
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="toPersonalCenter"><i style="padding-right: 5px" class="el-icon-user"></i>个人中心</el-dropdown-item>
            <el-dropdown-item command="toShortcutMenuList"><i style="padding-right: 5px" class="el-icon-menu"></i>快捷入口</el-dropdown-item>
            <el-dropdown-item command="logout"><i style="padding-right: 5px" class="el-icon-switch-button"></i>退出系统</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <div class="app">
      <div class="aside">
        <div class="menu">
          <el-menu router :default-active="$route.path" class="menu" @open="handleOpen" @close="handleClose"
            :unique-opened="true" text-color="#76838f" active-text-color="#409EFF" :collapse="isCollapse">
            <el-menu-item :index="dashboardMenu.url" style="border-bottom: #e4e4e4 1px solid;">
              <img src="/static/icon/menu/系统仪表.png" width="20" height="20">
              <span slot="title">{{dashboardMenu.name}}</span>
            </el-menu-item>
            <menu-tree :key="menu.code" :menu="menu" :index="index + ''" v-for="(menu,index) in asideMenus"></menu-tree>
          </el-menu>
        </div>
        <div class="sidebar-toggle" @click="sidebarToggle">
          <div class="icon-left">
            <i class="el-icon-back"></i>
          </div>
        </div>
      </div>
      <div class="app-body">
        <nav-bar id="nav-bar" v-if="isRebuildNavBar" style="position: fixed;top: 0;"></nav-bar>
        <div id="mainContainer" class="main-container">
          <router-view></router-view>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import Stomp from 'stompjs'
import MenuTree from '../../common/component/menu-tree'
import NavBar from './nav-bar'
import Screenfull from 'screenfull'

export default {
  name: 'index',
  components: {
    MenuTree,
    NavBar
  },

  inject: ['reload'],
  data () {
    return {
      siteName: '',
      dashboardMenu: {
        name: '系统首页',
        url: '/DashboardA100401'
      },
      isCollapse: false,
      projectList: [],
      selectedProjectId: 0,
      myUnreadNoticeCount: {},
      client: Stomp.client(Vue.$rabbitmqURL),
      notifyInstances: [],
      oneLevelMenus: this.loginContext.getLoginContext().oneLevelMenus, // 头部菜单栏：只展示一级菜单
      asideMenus: null, // 左侧菜单导航栏
      userAvatar: '../../../static/icon/demo/user7-128x128.jpg',
      isRebuildNavBar: true
    }
  },
  created: function () {
    this.loadProjectSelect()
    this.getUnreadNoticeCount()
    this.connect()
    this.toDashboard()
  },
  mounted: function () {
    document.getElementById('mainContainer').style.minHeight = 'calc(100vh - 139px)'

    if (!this.isCollapse) {
      document.body.classList.remove('sidebar-hidden')
    } else {
      document.body.classList.add('sidebar-hidden')
    }

    setTimeout(() => {
      this.NavBarWidth()
    }, 1000)

    if (this.loginContext.getLoginContext().oneLevelMenus != null) {
      this.loadAsideMenu(this.loginContext.getLoginContext().oneLevelMenus[0])
    }
  },
  destroyed: function () {
    if (this.client != null) {
      this.client.disconnect()
    }

    if (this.notifyInstances != null && this.notifyInstances.length > 0) {
      for (let i = 0; i < this.notifyInstances.length; i++) {
        this.notifyInstances[i].close()
      }
      this.notifyInstances = []
    }
  },
  methods: {
    screenfullToggle: function () { // 全屏全换
      if (!Screenfull.isEnabled) {
        this.$message({
          message: '你的浏览器不支持全屏！',
          type: 'warning'
        })
        return false
      }
      Screenfull.toggle()
    },
    NavBarWidth () {
      let navBar = document.getElementById('nav-bar')
      if (!navBar) return
      let sidebarClose = document.body.classList.contains('sidebar-close')
      if (sidebarClose) {
        navBar.style.width = '100%'
        return
      }
      if (this.isCollapse) navBar.style.width = 'calc(100% - 64px)'
      else navBar.style.width = 'calc(100% - 230px)'
    },
    sidebarToggle (e) { // 简显/全显左侧菜单切换事件
      e.preventDefault()
      if (this.isCollapse) {
        document.body.classList.remove('sidebar-hidden')
        this.isCollapse = false
      } else {
        document.body.classList.add('sidebar-hidden')
        this.isCollapse = true
      }
      this.NavBarWidth()
    },
    hiddenSidebar (e) { // 隐藏/显示左侧菜单事件
      e.preventDefault()
      document.body.classList.toggle('sidebar-close')
      this.NavBarWidth()
    },
    handleOpen (key, keyPath) {
      // console.log(key, keyPath);
    },
    handleClose (key, keyPath) {
      // 关闭菜单
    },

    connect: function () {
      const headers = {
        'login': Vue.$rabbitmqUserName,
        'passcode': Vue.$rabbitmqPassword,
        'host': Vue.$profilesActive,
        'heart-beat': '0,0'
      }
      this.client.connect(headers, this.onConnected, this.onFailed)
    },
    onConnected: function (frame) {
      // 订阅频道
      const topic = '/exchange/exchange-publishnotification/key-publishnotification'
      this.client.subscribe(topic, this.responseCallback, this.onFailed)
    },
    onFailed: function (frame) {
      console.error('MQ failed: ' + frame)
    },
    responseCallback: function (frame) {
      if (!Vue.$isNullOrIsBlankOrIsUndefined(frame.body)) {
        let data = JSON.parse(frame.body)
        if (data.opt === '1') { // 有新消息发布，则查询是否有我的通知，有则弹出来
          this.showNotify(data)
          this.getUnreadNoticeCount()
        } else if (data.opt === '2') { // 有消息被读取，则重新查询我的未读消息数量
          this.getUnreadNoticeCount()
        }
      }
    },
    showNotify: function (data) { // 弹出通知框
      Vue.$ajax({
        method: 'get',
        url: Vue.$adminServerURL + '/web/v1/IndexController/isMyNotice/' + data.receiverType + '/' + data.receiver
      }).then(res => {
        if (res.data.flag === 'SUCCESS') {
          if (res.data.obj === true || res.data.obj === 'true') {
            const h = this.$createElement
            this.closeAllNotice()
            let notifyInstance = this.$notify({
              title: '系统消息',
              message: h('i', {
                style: 'color: red'
              }, data.title),
              type: 'info',
              position: 'bottom-right',
              duration: 30000,
              onClick: this.showMyNotice
            })
            this.notifyInstances.push(notifyInstance)
          }
        }
      })
    },
    showMyNotice: function () {
      this.toMyNoticeList()
      this.closeAllNotice()
    },
    getUnreadNoticeCount: function () { // 获取未读的通知数量
      Vue.$ajax({
        method: 'get',
        url: Vue.$adminServerURL + '/web/v1/IndexController/getUnreadNoticeCount'
      }).then(res => {
        if (res.data.flag === 'SUCCESS') {
          let obj = res.data.obj
          this.myUnreadNoticeCount = obj
        } else {
          if (!Vue.$isNullOrIsBlankOrIsUndefined(res.data.message)) {
            this.$message({
              message: res.data.message,
              type: 'warning'
            })
          }
        }
      })
    },
    toMyNoticeList: function () {
      this.$router.push({
        path: '/MyNoticeList'
      })
    },
    closeAllNotice: function () {
      if (this.notifyInstances != null && this.notifyInstances.length > 0) {
        for (let i = 0; i < this.notifyInstances.length; i++) {
          this.notifyInstances[i].close()
        }
        this.notifyInstances = []
      }
    },
    handleCommandMessage: function (command) {
      if (command === 'A102107') { // 系统通知
        this.toMyNoticeList()
      } else if (command === 'A102108') { // 报警
        this.toMyNoticeList()
      }
    },
    handlePersonalCenter (command) {
      if (command === 'logout') { // 登出
        this.logout()
      } else if (command === 'toPersonalCenter') { // 修改密码
        this.$router.push({
          path: '/PersonalCenter'
        })
      } else if (command === 'toShortcutMenuList') {
        this.$router.push({
          path: '/ShortcutMenuList'
        })
      }
    },
    loadProjectSelect: function () {
      this.projectList = sessionStorage.getItem('my-project-list') == null ? null : JSON.parse(sessionStorage.getItem(
        'my-project-list'))
      let projectId = this.loginContext.getLoginContext().projectId
      if (!Vue.$isNullOrIsBlankOrIsUndefined(projectId)) {
        this.selectedProjectId = projectId
        this.switchProjectBySystem(projectId)
      } else {
        if (this.projectList != null && this.projectList.length > 0) {
          this.selectedProjectId = this.projectList[0].id
          this.switchProjectBySystem(this.projectList[0].id)
        }
      }
    },
    switchProjectBySystem: function (id) {
      Vue.$ajax({
        method: 'post',
        url: Vue.$adminServerURL + '/web/v1/IndexController/switchProject/' + id
      }).then(res => {
        if (res.data.flag === 'SUCCESS') {
          this.loginContext.setProjectToLoginContext(id)
        } else {
          if (!Vue.$isNullOrIsBlankOrIsUndefined(res.data.message)) {
            this.$message({
              message: res.data.message,
              type: 'warning'
            })
          }
        }
      })
    },
    switchProjectByUser: function (id) {
      Vue.$ajax({
        method: 'post',
        url: Vue.$adminServerURL + '/web/v1/IndexController/switchProject/' + id
      }).then(res => {
        if (res.data.flag === 'SUCCESS') {
          this.loginContext.setProjectToLoginContext(id)
          this.reload()
        } else {
          if (!Vue.$isNullOrIsBlankOrIsUndefined(res.data.message)) {
            this.$message({
              message: res.data.message,
              type: 'warning'
            })
          }
        }
      })
    },
    logout: function () {
      let xAuthToken = sessionStorage.getItem('x-auth-token')
      this.$confirm('您确定要退出登录吗, 是否继续?', '询问', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        Vue.$ajax({
          method: 'post',
          url: Vue.$adminServerURL + '/web/v1/UserLogoutController/logout/' + xAuthToken
        }).then(res => {
          if (res.data.flag === 'SUCCESS') {
            this.$router.push({
              path: '/Login'
            })
          } else {
            if (!Vue.$isNullOrIsBlankOrIsUndefined(res.data.message)) {
              this.$message({
                message: res.data.message,
                type: 'warning'
              })
            }
          }
        })
      }).catch(() => {})
    },
    loadAsideMenu: function (data) {
      // 重新加载导航 S
      this.isRebuildNavBar = false
      sessionStorage.removeItem('lastVisitMenu')
      this.toDashboard()
      // 重新加载导航 E

      Vue.$ajax({
        method: 'post',
        url: Vue.$adminServerURL + '/web/v1/IndexController/buildAsideMenuJson?pcode=' + data.code
      }).then(res => {
        this.isRebuildNavBar = true
        if (res.data.flag === 'SUCCESS') {
          this.siteName = data.description
          this.asideMenus = res.data.obj
        } else {
          if (!Vue.$isNullOrIsBlankOrIsUndefined(res.data.message)) {
            this.$message({
              message: res.data.message,
              type: 'warning'
            })
          }
        }
      })
    },
    toDashboard: function () {
      if (this.loginContext.getLoginContext().userType === 'A100403') {
        this.dashboardMenu.url = '/DashboardA100403'
      } else if (this.loginContext.getLoginContext().userType === 'A100406') {
        this.dashboardMenu.url = '/DashboardA100406'
      } else if (this.loginContext.getLoginContext().userType === 'A100409') {
        this.dashboardMenu.url = '/DashboardA100409'
      } else if (this.loginContext.getLoginContext().userType === 'A100410') {
        this.dashboardMenu.url = '/DashboardA100410'
      } else if (this.loginContext.getLoginContext().userType === 'A100411') {
        this.dashboardMenu.url = '/DashboardA100411'
      }
      this.$router.push({
        path: this.dashboardMenu.url
      })
    }
  }
}
</script>
<style lang="less">
  .sidebar-hidden {
    .header {
      .logo {
        .big {
          display: none;
        }

        .min {
          display: block;
        }

        width: 64px;
      }

    }

    .aside {
      .sidebar-toggle {
        .icon-left {
          transform: rotate(180deg);
        }
      }
    }

    .main {
      .app-body {
        margin-left: 64px;
      }
    }
  }

  .sidebar-close {
    .header {
      .logo {
        width: 0;
        overflow: hidden;
      }
    }

    .aside {
      margin-left: -230px;
    }

    .main {
      .app-body {
        margin-left: 0;
      }
    }
  }

  .sidebar-hidden.sidebar-close {
    .aside {
      margin-left: -64px;
    }
  }

  .main {
    display: flex;

    .el-menu:not(.el-menu--collapse) {
      width: 230px;
    }

    .app {
      width: 100%;
    }

    .aside {
      position: fixed;
      margin-top: 50px;
      z-index: 10;
      border-right: 1px solid #e4e4e4;
      border-bottom: 1px solid #e4e4e4;
      transition: all 0.3s ease-in-out;

      .el-menu {
        border: 0;
      }

      .menu {
        overflow-y: auto;
        height: calc(~'100vh - 100px');
        border-right: none;
      }

      .menu::-webkit-scrollbar {
        width: 4px;
        height: 4px;
      }

      .menu::-webkit-scrollbar-thumb {
        background-color: #e4e4e4;
      }

      .sidebar-toggle {
        position: relative;
        width: 100%;
        height: 50px;
        background-color: #ecf0f5;
        color: #303133;
        cursor: pointer;

        .icon-left {
          position: absolute;
          display: flex;
          align-items: center;
          justify-content: center;
          right: 0;
          width: 64px;
          height: 100%;
          font-size: 20px;
          transition: all 0.3s ease-in-out;
        }
      }
    }

    .app-body {
      margin-left: 230px;
      -webkit-transition: margin-left 0.3s ease-in-out;
      transition: margin-left 0.3s ease-in-out;
    }

    .main-container {
      margin-top: 88px;
      padding: 6px;
      min-height: calc(~'100vh - 101px');
    }
  }

  .header {
    width: 100%;
    position: fixed;
    display: flex;
    height: 50px;
    background-color: #009688;
    z-index: 10;

    .logo {
      .min {
        display: none;
      }

      width: 230px;
      height: 50px;
      text-align: center;
      line-height: 50px;
      color: #fff;
      background-color: #108B8B;
      -webkit-transition: width 0.35s;
      transition: all 0.3s ease-in-out;
    }

    .right {
      position: absolute;
      right: 0;
    }

    .header-btn {
      .el-badge__content {
        top: 14px;
        right: 7px;
        text-align: center;
        font-size: 11px;
        padding: 0 3px;
        border: none;
        white-space: nowrap;
        vertical-align: baseline;
        border-radius: .25em;
      }

      overflow: hidden;
      height: 50px;
      display: inline-block;
      text-align: center;
      line-height: 50px;
      cursor: pointer;
      padding: 0 14px;
      color: #fff;

      &:hover {
        background-color: #367fa9
      }
    }
  }
</style>
